#pragma once

#include <iostream>
#include "Protocol.hpp"

enum{
    DIV_ZERO = 1,
    MOD_ZERO,
    OTHER_OPER
};

class ServerCal
{
public:
    ServerCal()
    {
    }
    ~ServerCal()
    {
    }
    // 运算+-*/%
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp._result = req.x + req.y;
            break;
        case '-':
            resp._result = req.x - req.y;
            break;
        case '*':
            resp._result = req.x * req.y;
            break;
        case '/':
            {
                if (req.y == 0)
                    resp._code = DIV_ZERO;
                else
                    resp._result = req.x / req.y;
            }
            break;
        case '%':
            {
                if (req.y == 0)
                    resp._code = OTHER_OPER;
                else
                    resp._result = req.x % req.y;
            }
            break;
        default:
            resp._code = OTHER_OPER;
            break;
        }

        return resp;
    }
    // 接收输入的运算式并返回运算结果
    std::string Calculator(std::string &package)
    {
        // 获取运算式
        std::string content;
        bool r = Decode(package, content);
        if (!r)
            return "";

        // 获取拆解下的两个操作数和一个运算符
        Request req;
        r = req.Deserialize(content);
        if (!r)
            return "";

        // 开始运算
        content = "";
        Response resp = CalculatorHelper(req);

        // 拼接结果表达式
        resp.Serialize(content);
        content = Encode(content);

        return content;
    }
};